<?php
declare (strict_types=1);

namespace app\user\model\user;

use app\common\model\BaseModel;
use app\course\model\coupon\CouponUser;
use app\school\model\school\School;
use think\model\relation\BelongsTo;
use think\model\relation\HasOne;

/**
 * 定义活动数据模型
 */
class TicketCoupon extends BaseModel
{
    /**
     * 表名
     *
     * @var string
     */
    protected $name = 'market_ticket_coupon';

    protected $type = [
        'ext_data'      => 'array',
        'derive_stime'  => 'integer',
        'derive_etime'  => 'integer',
        'create_time'   => 'integer',
        'update_time'   => 'integer',
        'maxprice'      => 'float',
        'price'         => 'float',
        'discount'      => 'float',
        'coupon_type'   => 'integer',
        'is_receive'    => 'integer',
        'ticket_id'     => 'integer',
        'mhm_id'        => 'integer',
        'effective_day' => 'integer'
    ];

    /**
     * 全局查询范围
     *
     * @var [type]
     */
    protected $globalScope = ['receive'];

    /**
     * 限制机构条件
     *
     * @param $query
     */
    public function scopeMhm($query)
    {
        $query->where('mhm_id', request()->mhm_id);
    }

    public function scopeReceive($query)
    {
        $query->where('is_receive', 1);
    }

    /**
     * mhmTitle
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/08/30
     *
     * @return BelongsTo
     */
    public function mhmTitle()
    {
        return $this->belongsTo(School::class, 'mhm_id')->bind(['school_name' => 'title']);
    }

    public function useTime()
    {
        return $this->hasOne(CouponUser::class, 'ticket_id')->where('user_id', request()->mid)->bind(['use_stime' => 'create_time', 'use_etime' => 'end_time']);
    }

    /**
     * 用户可使用活动券
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/09/11
     *
     * @return HasOne
     */
    public function userHas()
    {
        return $this->hasOne(CouponUser::class, 'ticket_id')->where('user_id', request()->mid);
    }

    /**
     * 用户领取了的卡券且未使用
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/09/11
     *
     * @return HasOne
     */
    public function userHasUnused()
    {
        return $this->hasOne(CouponUser::class, 'ticket_id')->where('user_id', request()->mid)->where('status', 0)->bind(['user_has' => 'id']);
    }
}
